package com.cfuture08.eweb4j.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import com.cfuture08.eweb4j.cache.SingleBeanCache;
import com.cfuture08.eweb4j.config.ConfigConstant;
import com.cfuture08.eweb4j.config.bean.ConfigBean;
import com.cfuture08.eweb4j.config.log.LogFactory;
import com.cfuture08.eweb4j.orm.RowMapping;
import com.cfuture08.eweb4j.orm.cache.LevelOneCache;
import com.cfuture08.eweb4j.orm.cache.SqlResultCache;
import com.cfuture08.util.LogUtil;

public class JdbcTemplate {

	public static boolean update(Class<?> clazz, String... sqls)
			throws Exception {
		boolean flag = false;
		Connection con = null;
		StringBuilder sql = new StringBuilder();
		ConnectionManager cm = ConnectionManager.getInstance();
		try {
			int[] result = new int[sqls.length];
			con = cm.getConnection();
			con.setAutoCommit(false);
			for (int i = 0; i < sqls.length; ++i) {
				sql.append(sqls[i]);
				PreparedStatement pstmt = con.prepareStatement(sqls[i]);
				result[i] = pstmt.executeUpdate();
				pstmt.close();
				String debug = ((ConfigBean) SingleBeanCache
						.get(ConfigConstant.CONFIGBEAN_ID)).getOrm().getDebug();
				StringBuilder sb = new StringBuilder();
				sb.append("ORM:执行sql：").append(sqls[i]);
				sb.append("影响行数：").append(result[i]).append(";\n");
				if ("true".equals(debug) || "1".equals(debug)) {
					System.out.println(sb.toString());
				}
				LogFactory.getORMLogger().write(sb.toString());
				LogUtil.getLogger().info(sb.toString());
			}
			for (int i : result) {
				if (i > 0) {
					flag = true;
				} else {
					flag = false;
					break;
				}
			}

			if (flag) {
				con.commit();
				// 清空对应vo类缓存
				LevelOneCache.remove(clazz);
			} else {
				con.rollback();
			}
		} catch (Exception e) {
			con.rollback();
			flag = false;
			String error = sql.append("执行出错了！").toString();
			LogUtil.getLogger().error(error, e);
			LogFactory.getORMLogger().write(error);
			throw e;
		}
		if (con != null) {
			con.close();
		}

		return flag;
	}

	public static boolean updateWhithArgs(Class<?> clazz, String sql,
			Object... args) throws Exception {
		boolean result = false;
		Connection con = null;
		ConnectionManager cm = ConnectionManager.getInstance();
		try {
			boolean success = false;
			con = cm.getConnection();
			con.setAutoCommit(false);
			PreparedStatement pstmt = con.prepareStatement(sql);
			for (int i = 0; i < args.length; ++i) {
				pstmt.setObject(i + 1, args[i]);
			}
			int rs = pstmt.executeUpdate();
			String debug = ((ConfigBean) SingleBeanCache
					.get(ConfigConstant.CONFIGBEAN_ID)).getOrm().getDebug();
			StringBuilder sb = new StringBuilder();
			sb.append("ORM:执行sql：").append(sql);
			sb.append("影响行数：").append(result).append(";\n");
			if ("true".equals(debug) || "1".equals(debug)) {
				System.out.println(sb.toString());
			}
			LogUtil.getLogger().info(sb.toString());
			LogFactory.getORMLogger().write(sb.toString());
			pstmt.close();
			result = rs > 0 ? true : false;

			if (success) {
				con.commit();
				// 清空对应vo类缓存
				LevelOneCache.remove(clazz);
			} else {
				con.rollback();
			}
		} catch (Exception e) {
			con.rollback();
			String error = new StringBuilder(sql).append("执行出错了！").toString();
			LogUtil.getLogger().error(error, e);
			LogFactory.getORMLogger().write(error);
			throw e;
		}

		if (con != null) {
			con.close();
		}
		return result;
	}

	public static <T> List<T> getResultSet(Class<T> clazz, String... sqls)
			throws Exception {
		List<T> list = null;
		SqlResultCache src = null;
		// -------缓存-------
		StringBuilder sb1 = new StringBuilder();
		for (String s : sqls) {
			sb1.append(s);
		}
		String sql = sb1.toString();
		// 如果在一级缓存里面找到该vo类的缓存
		if (LevelOneCache.containsKey(clazz)) {
			src = LevelOneCache.get(clazz);
			// 如果在一级缓存里面找到该sql语句的缓存
			if (src.containsKey(sql)) {
				list = (List<T>) LevelOneCache.get(clazz).get(sql);
				// ----------log-------
				String debug = ((ConfigBean) SingleBeanCache
						.get(ConfigConstant.CONFIGBEAN_ID)).getOrm().getDebug();
				int count = list == null ? 0 : list.size();
				StringBuilder sb = new StringBuilder();
				sb.append("ORM:从缓存中取出结果集,对应的sql语句为：").append(sql);
				sb.append("查出结果数：").append(count).append(";\n");
				if ("true".equals(debug) || "1".equals(debug)) {
					System.out.println(sb.toString());
				}
				LogUtil.getLogger().info(sb.toString());
				LogFactory.getORMLogger().write(sb.toString());
				// ----------------
				return list;
			}
		} else {
			src = new SqlResultCache();
			LevelOneCache.add(clazz, src);
		}

		list = getResultSetWithoutCache(clazz, sqls);
		if (list != null) {
			src.add(sql, list);
		}

		return list;
	}

	public static <T> List<T> getResultSetWithArgs(Class<T> clazz, String sql,
			Object... args) throws Exception {
		List<T> list = null;
		SqlResultCache src = null;
		// -------缓存-------
		// 如果在一级缓存里面找到该vo类的缓存
		if (LevelOneCache.containsKey(clazz)) {
			src = LevelOneCache.get(clazz);
			// 如果在一级缓存里面找到该sql语句的缓存
			if (src.containsKey(sql)) {
				list = (List<T>) LevelOneCache.get(clazz).get(sql);
				// ----------log-------
				String debug = ((ConfigBean) SingleBeanCache
						.get(ConfigConstant.CONFIGBEAN_ID)).getOrm().getDebug();
				int count = list == null ? 0 : list.size();
				StringBuilder sb = new StringBuilder();
				sb.append("ORM:从缓存中取出结果集,对应的sql语句为：").append(sql);
				sb.append("查出结果数：").append(count).append(";\n");
				if ("true".equals(debug) || "1".equals(debug)) {
					System.out.println(sb.toString());
				}
				LogUtil.getLogger().info(sb.toString());
				LogFactory.getORMLogger().write(sb.toString());
				// ----------------
				return list;
			}
		} else {
			src = new SqlResultCache();
			LevelOneCache.add(clazz, src);
		}

		list = getResultSetWithoutCache(clazz, sql, args);
		if (list != null) {
			src.add(sql, list);
		}

		return list;
	}

	public static <T> List<T> getResultSetWithoutCache(Class<T> clazz,
			String... sqls) throws Exception {
		List<T> list = null;
		Connection con = null;
		int i = 0;
		ConnectionManager cm = ConnectionManager.getInstance();
		try {
			con = cm.getConnection();
			for (i = 0; i < sqls.length; i++) {
				PreparedStatement pstmt = con.prepareStatement(sqls[i]);
				ResultSet rs = pstmt.executeQuery();
				list = RowMapping.mapRow(rs, clazz);

				rs.close();
				pstmt.close();
				// ----------log-------
				String debug = ((ConfigBean) SingleBeanCache
						.get(ConfigConstant.CONFIGBEAN_ID)).getOrm().getDebug();
				int count = list == null ? 0 : list.size();
				StringBuilder sb = new StringBuilder();
				sb.append("ORM:执行sql：").append(sqls[i]);
				sb.append("查出结果数：").append(count).append(";\n");
				if ("true".equals(debug) || "1".equals(debug)) {
					System.out.println(sb.toString());
				}
				LogFactory.getORMLogger().write(sb.toString());
				LogUtil.getLogger().info(sb.toString());
				// ----------------
			}
		} catch (Exception e) {
			String error = new StringBuilder(sqls[i]).append("执行出错了！").toString();
			LogUtil.getLogger().error(error,e);
			LogFactory.getORMLogger().write(error);
			throw e;
		}
		if (con != null) {
			con.close();
		}

		return list;
	}

	public static <T> List<T> getResultSetWithoutCache(Class<T> clazz,
			String sql, Object... args) throws Exception {
		List<T> list = null;
		Connection con = null;
		ConnectionManager cm = ConnectionManager.getInstance();
		try {
			con = cm.getConnection();

			PreparedStatement pstmt = con.prepareStatement(sql);
			for (int i = 0; i < args.length; ++i) {
				pstmt.setObject(i + 1, args[i]);
			}
			ResultSet rs = pstmt.executeQuery();
			list = RowMapping.mapRow(rs, clazz);

			rs.close();
			pstmt.close();
			// ----------log-------
			String debug = ((ConfigBean) SingleBeanCache
					.get(ConfigConstant.CONFIGBEAN_ID)).getOrm().getDebug();
			int count = list == null ? 0 : list.size();
			StringBuilder sb = new StringBuilder();
			sb.append("ORM:执行sql：").append(sql);
			sb.append("查出结果数：").append(count).append(";\n");
			if ("true".equals(debug) || "1".equals(debug)) {
				System.out.println(sb.toString());
			}
			LogUtil.getLogger().info(sb.toString());
			LogFactory.getORMLogger().write(sb.toString());
			// ----------------

		} catch (Exception e) {
			String error = new StringBuilder(sql).append("执行出错！").toString();
			LogUtil.getLogger().error(error, e);
			LogFactory.getORMLogger().write(error);
			throw e;
		}
		if (con != null) {
			con.close();
		}

		return list;
	}
}
